<template>

  <div class="app-container">
    <el-card class="box-card" style="margin-top: 20px">
      <div style="width: 150px; height: 10px; background-color: var(--primary-color);position:relative;top:-15px"></div>
      <div class="title20Class">
        <svg-icon icon-class="info" class="svgClass"/>
        基本信息
      </div>
      <el-divider content-position="left"></el-divider>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickName">
              <el-input size="small" v-model="form.nickName" placeholder="请输入"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录名" prop="userName">
              <el-input size="small" v-model="form.userName" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属组织机构" prop="deptName">
              <el-cascader size="small" :options="deptOptions" clearable
                           v-model="form.deptId" filterable
                           :props="{ value:'value',Label:'deptName',emitPath:false,checkStrictly: true }"
                           @change="changeHandle"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位" size="small">
              <el-cascader size="small" :options="postOptions" clearable :show-all-levels="false"
                           v-model="form.postIds" filterable style="width: 100%" placeholder="请选择岗位"
                           :props="{ value:'id',Label:'label',multiple: true ,checkStrictly: true,emitPath:false}"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phonenumber">
              <el-input size="small" v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds" size="small">
              <el-select v-model="form.roleIds" multiple placeholder="请选择角色" style="width: 100%;">
                <el-option
                  size="small"
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input size="small" v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="dialog-footer" style="text-align: center;height:80px;line-height: 80px;">
        <el-button size="small" @click="cancel">取 消</el-button>
        <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-card>
    <el-dialog title="组织机构" :visible.sync="chooseDeptOpen" append-to-body width="600px">
      <choose-dept @deptValue="deptValue"></choose-dept>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="deptCancel">取 消</el-button>
        <el-button size="small" type="primary" @click="deptSubmitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect, deptControlTree
} from '@/api/system/user'
import { getToken } from '@/utils/auth'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import ChooseProcess from '@/plugins/package/tree/chooseProcess'
import ChooseDept from '@/plugins/package/tree/chooseDept'
import { Base64 } from 'js-base64'
import { postControlTree } from '@/api/system/post'

export default {
  name: 'User',
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { Treeselect, ChooseProcess, ChooseDept },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      deptId: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {
        password: '',
        passwordConfirm: ''
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      userId: undefined,
      chooseDeptOpen: false,
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '登录名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        passwordConfirm: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' }
        ],
        deptName: [
          { required: true, message: '所属组织机构不能为空', trigger: 'blur' }
        ],
        postIds: [
          { required: true, message: '岗位不能为空', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: '角色不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  activated() {
    console.log('__activated__')
    this.handleUpdate()
    this.getDeptTree()
  },
  methods: {
    /**
     * 部门子页面传参到父页面
     */
    deptValue(data) {
      this.deptName = data.label
      this.deptId = data.id
    }
    ,
    /**
     * 主办部门选择-确定
     */
    deptSubmitForm() {
      //form为表单的ref名称，fields为该表单下需要验证的所有字段，tarKeyArr为需要重置的所有字段
      for (let item of this.$refs.form.fields) {
        if ('deptName'.indexOf(item.prop) !== -1) {
          item.resetField()
        }
      }

      this.form.deptName = this.deptName
      this.form.deptId = this.deptId
      this.chooseDeptOpen = false
    }
    ,
    /**
     * 主办部门选择-取消
     */
    deptCancel() {
      this.chooseDeptOpen = false
    }
    ,
    /**
     * 部门弹出
     */
    chooseDeptHandle() {
      this.chooseDeptOpen = true
    }
    ,
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    }
    ,
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptControlTree().then(response => {
        this.deptOptions = response.data
        console.log('this.deptOptions', this.deptOptions)
      })
    }
    ,
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }
    ,
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.handleQuery()
    }
    ,
    // 取消按钮
    cancel() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    }
    ,
    /** 修改按钮操作 */
    handleUpdate() {
      const userId = this.$route.query.userId
      getUser(userId).then(response => {
        this.form = response.data.user
        // this.postOptions = response.data.posts
        this.roleOptions = response.data.roles
        this.$set(this.form, 'postIds', response.data.postIds)
        this.$set(this.form, 'roleIds', response.data.roleIds)
        this.form.password = ''
        this.form.passwordConfirm = ''
        this.getPost(this.form.deptId)
      })
    }
    ,
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          //判断确认密码是否正确
          if (this.form.password !== this.form.passwordConfirm) {
            this.$modal.msgError('两次输入的密码不相同')
            return false
          }
          updateUser(Object.assign(this.form, {
            userName: Base64.encode(this.form.userName),
            password: Base64.encode(this.form.password),
            passwordConfirm: Base64.encode(this.form.passwordConfirm)
          })).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.go(-1)
          })
        }
      })
    },

    changeHandle() {
      this.getPost(this.form.deptId)
    },
    getPost(deptIds) {
      postControlTree(deptIds).then(res => {
        this.postOptions = res.data
        console.log('res', res)
      })
    }
  }
}
</script>
